package com.example.amusic

import android.Manifest
import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.provider.Settings
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.amusic.screen.Home
import com.example.amusic.service.CustomMediaServiceHandler
import com.example.amusic.service.MusicService
import com.example.amusic.ui.theme.AMusicTheme
import com.example.amusic.viewmodel.MainIntent
import com.example.amusic.viewmodel.MainViewModel
import com.example.amusic.viewmodel.PlayViewModel
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale
import kotlinx.coroutines.launch
import kotlin.math.cos


val TAG: String = "MainActivity_TAG"

class MainActivity : ComponentActivity() {
    private val mainViewModel by viewModels<MainViewModel>()
    private val playViewModel by viewModels<PlayViewModel>()

    @RequiresApi(Build.VERSION_CODES.R)
    override fun onCreate(savedInstanceState: Bundle?) {
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        if (playViewModel.recreateActivity.value == true) {
            playViewModel.customMediaServiceHandler?.coroutineScope = lifecycleScope
            playViewModel.activityRecreateDone()
        } else {
            startMusicService()
        }

        playViewModel.activityRecreate()

        mainViewModel.dispatch(MainIntent.InitNetWorkMonitor(this))


        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                mainViewModel.mainState.value.isNetWorkOnline.collect {
                    Log.e("TAG_NETWORK", "监听网络状态:  $it ")
                }
            }
        }

        setContent {

            //TODO 1 修改状态栏颜色
//            val statusBarLight = Color.WHITE
//            val statusBarDark = Color.BLACK
//            val navigationBarLight = Color.GREEN
//            val navigationBarDark = Color.BLUE
//            val isDarkMode = isSystemInDarkTheme()
//            val context = LocalContext.current as ComponentActivity
//            DisposableEffect(isDarkMode) {
//                context.enableEdgeToEdge(
//                    statusBarStyle = if (!isDarkMode) {
//                        SystemBarStyle.light(
//                            statusBarLight,
//                            statusBarDark
//                        )
//                    } else {
//                        SystemBarStyle.dark(
//                            statusBarDark
//                        )
//                    },
//
//                    navigationBarStyle = if (!isDarkMode) {
//                        SystemBarStyle.light(
//                            navigationBarLight,
//                            navigationBarDark
//                        )
//                    } else {
//                        SystemBarStyle.dark(
//                            navigationBarDark
//                        )
//                    }
//                )
//                onDispose { }
//            }

            //TODO 2
//            DisposableEffect(Unit) {
//                enableEdgeToEdge(
//                    statusBarStyle = SystemBarStyle.auto(
//                        android.graphics.Color.TRANSPARENT,
//                        android.graphics.Color.TRANSPARENT,
//                    ) {false}, //这里的意思是是否需要检测深色主题模式，我们使用自己的背景，所以不需要直接设置为false,下面也是一样的
//                    navigationBarStyle = SystemBarStyle.auto(
//                        lightScrim,
//                        darkScrim,
//                    ) { false},
//                )
//                onDispose {}
//            }

            AMusicTheme {
                setstatusBarColor(color = if (isSystemInDarkTheme()) Color.Black else Color.Transparent)
                // A surface container using the 'background' color from the theme
                Home(mainViewModel = mainViewModel, playViewModel = playViewModel)
            }
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        playViewModel.activityRecreate()
    }

    override fun onDestroy() {
        super.onDestroy()
        stopService()
    }

    private fun openAppSettingsScreen() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", packageName, null)
        intent.data = uri
        startActivity(intent)
    }


    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            if (service is MusicService.MusicBinder) {
                playViewModel.customMediaServiceHandler =
                    CustomMediaServiceHandler(
                        player = service.service.player,
                        mediaSession = service.service.mediaSession,
                        customMediaSessionCallback = service.service.customMediaSessionCallback,
                        context = service.service,
                        coroutineScope = lifecycleScope
                    )
                playViewModel.init()
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            playViewModel.customMediaServiceHandler = null
        }

    }

    private fun startMusicService() {
        if (playViewModel.recreateActivity.value != true) {
            val intent = Intent(this, MusicService::class.java)
            startService(intent)
            bindService(intent, serviceConnection, BIND_AUTO_CREATE)
        }
    }

    private fun stopService() {
        if (playViewModel.recreateActivity.value != true) {
            playViewModel.customMediaServiceHandler?.release()
            playViewModel.customMediaServiceHandler = null
            unbindService(serviceConnection)
        }
    }

}


/**
 * 通知权限
 */
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun NotificationsPermission() {
    val notificationPermissionState =
        rememberPermissionState(permission = Manifest.permission.POST_NOTIFICATIONS)
    if (notificationPermissionState.status.isGranted) {
        Text(text = "权限申请通过")
    } else {
        Column {
            val textToShow = if (notificationPermissionState.status.shouldShowRationale) {
                "通知权限拒绝会不显示通知信息"
            } else {
                "通知不可用"
            }

            Text(textToShow)
            Spacer(modifier = Modifier.height(8.dp))
            Button(onClick = { notificationPermissionState.launchPermissionRequest() }) {
                Text("申请通知权限")
            }
        }
    }
}

@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun Sample() {
    val locationPermissionsState = rememberMultiplePermissionsState(
        listOf(
            android.Manifest.permission.ACCESS_COARSE_LOCATION,
            android.Manifest.permission.ACCESS_FINE_LOCATION,
        )
    )

    if (locationPermissionsState.allPermissionsGranted) {
        Text("Thanks! I can access your exact location :D")
    } else {
        Column {
            val allPermissionsRevoked =
                locationPermissionsState.permissions.size == locationPermissionsState.revokedPermissions.size

            val textToShow = if (!allPermissionsRevoked) {
                // If not all the permissions are revoked, it's because the user accepted the COARSE
                // location permission, but not the FINE one.
                "Yay! Thanks for letting me access your approximate location. " + "But you know what would be great? If you allow me to know where you " + "exactly are. Thank you!"
            } else if (locationPermissionsState.shouldShowRationale) {
                // Both location permissions have been denied
                "Getting your exact location is important for this app. " + "Please grant us fine location. Thank you :D"
            } else {
                // First time the user sees this feature or the user doesn't want to be asked again
                "This feature requires location permission"
            }

            val buttonText = if (!allPermissionsRevoked) {
                "Allow precise location"
            } else {
                "Request permissions"
            }

            Text(text = textToShow)
            Spacer(modifier = Modifier.height(8.dp))
            Button(onClick = { locationPermissionsState.launchMultiplePermissionRequest() }) {
                Text(buttonText)
            }
        }
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!", modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    AMusicTheme {
        Greeting("Android")
    }
}

@Composable
fun setstatusBarColor(color: Color) {
    val view = LocalView.current
    if (!view.isInEditMode) {
        LaunchedEffect(key1 = true) {
            val window = (view.context as Activity).window
            window.statusBarColor = color.toArgb()
            window.navigationBarColor = color.toArgb()
        }
    }
}

private val lightScrim = android.graphics.Color.argb(0xe6, 0xFF, 0xFF, 0xFF)
private val darkScrim = android.graphics.Color.argb(0x80, 0x1b, 0x1b, 0x1b)
